package com.sunnada.edu.business.pieceApply.service;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.quartz.JobExecutionException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.sunnada.edu.business.pieceApply.dao.PieceApplyDao;
import com.sunnada.edu.business.setProcess.service.ProcessService;
import com.sunnada.edu.system.pub.common.AppContext;
import com.sunnada.edu.system.pub.common.EXCELObject;
import com.sunnada.edu.system.pub.dao.PubDao;
import com.sunnada.edu.system.pub.util.DateUtil;

@Service
@Transactional
public class PieceApplyServiceImpl implements PieceApplyService {
	private static final Logger logger = LoggerFactory.getLogger(PieceApplyServiceImpl.class);
	@Resource
	PieceApplyDao pieceApplyDao;
	
	@Resource
	ProcessService processService;

	@Override
	public int getExitSettlementCots(HashMap<String, String> params) {
		return pieceApplyDao.getExitSettlementCots(params);
	}

	@Override
	public List<?> findExitSettlement(HashMap<String, String> params)  {
		List<?> workerList=pieceApplyDao.findExitSettlement(params);
		return workerList;
	}

	@Override
	public String attendanceDelete(HashMap<String, String> params) {
		String msg = "";
		int num = pieceApplyDao.attendanceDelete(params);
		if (num == 0) {
			msg = "删除失败!";
		}
		return msg;
	}

	@Override
	public String attenRecordAdd(HashMap<String, String> params) {
		String msg = "";
			int num = pieceApplyDao.attenRecordAdd(params);
			if (num == 0) {
				msg = "0";// 失败
			} else {
				msg = "1";// 成功
			}

		return msg;
	}

	@SuppressWarnings("unchecked")
	@Override
	public String attendanceUpdate(HashMap<String, String> params) {
		String msg = "";
			int num = pieceApplyDao.attendanceUpdate(params);
			if (num == 0) {
				msg = "0";// 失败
			} else {
				msg = "1";// 成功
			}
		return msg;
	}

	@Override
	public Map attendanceByRecId(HashMap<String, String> params) {
		return pieceApplyDao.attendanceByRecId(params);
	}
	@Override
	public void exportAttendance(HashMap<String, String> params, HttpServletRequest request, HttpServletResponse response) throws Exception {
		List dataList = pieceApplyDao.exportAttendance(params);
		String recId = UUID.randomUUID().toString();
		String realPath = request.getSession().getServletContext().getRealPath("/file/temp");
		EXCELObject s = new EXCELObject();
		s.seteFilePath(realPath);
		String[] titH = { "日期", "姓名", "工号", "所属班组","签到","签退", "工时", "考勤机","考勤状态","数据状态" };
		String[] titN = { "REC_TIME", "NAME", "JOBNO","GROUPID","SIGN_TIME","SIGNOUT_TIME","WORKING_HOURS","ATTENDANCE_MACHINE","ATTENDANCE_STATUS","DATE_STATUS" };
		s.setFname("考勤数据 "); // 临时文件名
		s.setTitle("考勤数据"); // 大标题名称
		s.setTitH(titH);
		s.setTitN(titN);
		s.setDataList(dataList);
		File exportFile = null;
		exportFile = s.setData();
		String excelName = "考勤数据" + DateUtil.getCurrentTime() + ".xls";
		s.exportExcel("考勤数据", excelName, exportFile, request, response);

	}

	@Override
	public String exitpayApply(HashMap<String, String> params) {
		String msg = "";
		//申请单ID
		String recId = UUID.randomUUID().toString();
		//根据流程类型回去，流程ID
		params.put("processType", "exitPayApply");
		String processId = processService.getProcessId(params);
		if(("").equals(processId)){
			msg = "退场结算审核流程未配置，请先进行配置！";
			return msg;
		}
		params.put("recId", recId);
		params.put("processId", processId);
		
		//将退场结算的申请单入录数据库
		params.put("applyTime", DateUtil.getNowTime());
		int num = pieceApplyDao.exitpayApply(params);
		if(num > 0){
			//将退场结算申请单对应的员工入录数据库
			List<HashMap<String, String>> list = new ArrayList<>();
			String recIds = params.get("recIds");
			String totalTimes[] = params.get("totalTime").split(",");
			String totalPieces[] = params.get("totalPiece").split(",");
			String totalShouldPays[] = params.get("totalShouldPay").split(",");
			String totalRealPays[] = params.get("totalRealPay").split(",");
			String totalNotPays[] = params.get("totalNotPay").split(",");
			String recIdss[] = recIds.split(",");
			for(int i = 0; i < recIdss.length; i++){
				HashMap<String, String> map = new HashMap<>();
				map.put("applyId", recId);
				map.put("workerId", recIdss[i]);
				map.put("totalTime", totalTimes[i]);
				map.put("totalPiece", totalPieces[i]);
				map.put("totalShouldPay", totalShouldPays[i]);
				map.put("totalRealPay", totalRealPays[i]);
				map.put("totalNotPay", totalNotPays[i]);
				map.put("rejectState", "1");
				map.put("loginId", params.get("loginUserId"));
				list.add(map);
			}
			num = pieceApplyDao.insertExitpayApplyWorkers(list);
			if(num > 0){
				//发起申请流程
				params.put("goDetailPage", "exitPayApply");
				msg = processService.startProcess(params);
				
				if(("").equals(msg)){
					params.put("step", "1");
					msg = updateWorkeState(params);
				}
			}else{
				msg = "退场结算审核提交失败！";
			}
			
			
		}else{
			msg = "退场结算审核提交失败！";
		}
		return msg;
	}

	/*
	 * 提交审核后修改员工表状态
	 */
	private String updateWorkeState(HashMap<String, String> params) {
		PubDao dao = AppContext.getInstance().getPubDao();
		String msg = "";
		String sql = "";
		int num = 0;
		if (("1").equals(params.get("step"))) {
			sql = "update t_worker set WORKER_STATE = '2' where REC_ID in ('"
					+ params.get("recIds").replaceAll(",", "','") + "')";
			num = dao.update(sql);
		} else {
			sql = "update t_worker_salary set REC_STATUS = '4', HTEDTIME = now(), HTSTATE = '2' where WORKER_ID in (select WORKER_ID from t_exitpay_apply_worker where apply_id = '"
					+ params.get("submitId")
					+ "' and REJECT_STATE = '1') ";
			num = dao.update(sql);
			
			
			String sqlWorker = "update t_worker set WORKER_STATE = '3' where REC_ID in (select WORKER_ID from t_exitpay_apply_worker where apply_id = '"
					+ params.get("submitId")
					+ "' and REJECT_STATE = '1') ";
			num = dao.update(sqlWorker);
		}
		
		if (num == 0) {
			msg = "工资发放审核提交失败！";
		}
		return msg;
	}
	
	@Override
	public List<?> getPieceApplyByRecid(HashMap<String, String> params) {
		return pieceApplyDao.getPieceApplyByRecid(params);
	}

	@Override
	public int getPieceApplyWorkerCots(HashMap<String, String> params) {
		return pieceApplyDao.getPieceApplyWorkerCots(params);
	}

	@Override
	public List<?> findPieceApplyWorker(HashMap<String, String> params) {
		return pieceApplyDao.findPieceApplyWorker(params);
	}

	@Override
	public String audit(HashMap<String, String> params) {
		PubDao dao = AppContext.getInstance().getPubDao();
		String msg = "";
		msg = processService.audit(params);
		
		//判断是不是流程的最后一步，如果是进行员工工资表状态更改
//		String sql = "select t.rec_id from t_process_staff t where t.parent_id = '" + params.get("auditId") + "'";
//		List<?> list = dao.selectList(sql);
//		if(list.size() == 0){
//			params.put("step", "2");
//			updateWorkeState(params);
//		}
		return msg;
	}

}
